package com.lanchewuyou.user.driver.bean;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

/**
 * 保险公司本地数据库操作类
 */
public class CompanyDB {
    private static final String COMPANY_DB_NAME = "companylist";
    private static final int COMPANY_VERSION = 1;
    private static CompanyDB companyDB;
    private SQLiteDatabase db;


    private CompanyDB(Context context) {
        CompanyOpenHelper dbHelper = new CompanyOpenHelper(context, COMPANY_DB_NAME, null, COMPANY_VERSION);
        db = dbHelper.getWritableDatabase();
    }

    public synchronized static CompanyDB getInstance(Context context) {
        if (companyDB == null) {
            companyDB = new CompanyDB(context);

        }
        return companyDB;
    }

    public void saveCompany(Company company) {
        if (company != null) {
            ContentValues values = new ContentValues();
            values.put("company_id", company.getId());
            values.put("company_name", company.getName());
            values.put("company_address", company.getAddress());
            values.put("company_shortname", company.getShortName());
            db.insert("Company", null, values);
        }

    }

    public void wipeCompany(){
        db.execSQL("DELETE FROM Company");
    }
    public String loadCompany(int companyId){
        Cursor cursor=db.rawQuery("select * from Company where company_id=?",new String[]{String.valueOf(companyId)});
        String companyName=new String();
        if(cursor.moveToFirst()) {

            companyName=cursor.getString(cursor.getColumnIndex("company_name"));
            return companyName;
        }
        return  null;
    }
    public List<Company> findCompanys(){
        List<Company> list=new ArrayList<Company>() ;
        Cursor cursor=db.query("Company",null,null,null,null,null,null);
        if(cursor.moveToFirst()){
            do{
                Company company=new Company();
                company.setId(cursor.getString(cursor.getColumnIndex("company_id")));
                company.setName(cursor.getString(cursor.getColumnIndex("company_name")));
                company.setAddress(cursor.getString(cursor.getColumnIndex("company_address")));
                company.setShortName(cursor.getString(cursor.getColumnIndex("company_shortname")));
                list.add(company);
            }while (cursor.moveToNext());
        }
        if(cursor!=null){
            cursor.close();
        }
        return  list;
    }

}
